package li.teng.joy.xcr.android;

import android.app.Activity;
import android.content.Context;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class XCRClient extends Activity {
	Button btnListenSsdp;
	Button btnListenVideo,btnCamera;
	SsdpAgent m_SsdpAgent;
	String m_DeviceIp;
	VideoServer m_VideoServer;
	TextView m_Msg;
	public static XCRClient m_Instance;
	
	public void updateMessage(final String  msg){
		this.runOnUiThread(new Runnable(){
			public void run() {
				m_Msg.setText("device ip = " + m_DeviceIp + " " + msg);
			} 
		});
	}
	
	@Override  
	public void onCreate(Bundle savedInstanceState) {  
		super.onCreate(savedInstanceState);  
		setContentView(R.layout.main);  
		m_Instance= this;
		
		Log.e("XInput", "create SsdpAgent");
		//get default parameters to ssdp		
		m_SsdpAgent = new SsdpAgent();
		m_SsdpAgent.m_VideoParameters.m_FrameRate = 25;
		m_SsdpAgent.m_VideoParameters.m_PixWidth = 320;
		m_SsdpAgent.m_VideoParameters.m_PixHeight = 240;
		m_SsdpAgent.m_VideoParameters.m_Format = MediaRecorder.VideoEncoder.H263;
		TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		m_SsdpAgent.m_VideoParameters.IMEI = telephonyManager.getDeviceId();
		
		m_DeviceIp = m_SsdpAgent.GetLocalIp();
		m_Msg = (TextView)(findViewById(R.id.msg));
		updateMessage("");
		
		
		m_VideoServer = new VideoServer();
		m_VideoServer.m_VideoParameters = m_SsdpAgent.m_VideoParameters;
		m_VideoServer.initCamera((SurfaceView)findViewById(R.id.surface));
		
		btnListenSsdp = (Button) findViewById(R.id.btnVideo);
		btnListenSsdp.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if(m_SsdpAgent.isListening()){
            		Log.d("XInput", "stop camera ");
            		m_SsdpAgent.Stop();
            		Log.d("XInput", "stop ssdp ok ");
            		m_VideoServer.stopListen();
            		Log.d("XInput", "stop video streaming ok ");
            		m_VideoServer.stopCamera();
            		Log.d("XInput", "stop camera ok ");
            		//m_VideoServer = null;
            		btnListenSsdp.setText("Start");
            	}else{
 	            	if(m_SsdpAgent.startListen()){
	            		btnListenSsdp.setText("Stop"); 
	            		Log.d("XInput", "start camera ");
	            		if(!m_VideoServer.startCamera()){
	            			updateMessage("open camera failed");
	            			return;
	            		}
	            		Log.d("XInput", "start camera stream service");
	            		m_VideoServer.startListen();
	            	}
            	}
            }
        });
		Log.e("XInput", "create VideoServer ok");
	}
	
	@Override
	protected void onDestroy() {
		Log.d("XInput", "onDestroy");
		super.onDestroy();
	}
}